<?php
require_once "./header.php";
require_once "./conn.php";
require_once "./usersession.php";
// 设置 JSON 响应头
header('Content-Type: application/json; charset=utf-8');
// 获取请求方法
$method = $_SERVER['REQUEST_METHOD'];

// 获取请求参数
$input = file_get_contents("php://input");
$params = json_decode($input, true);

// 路由处理
$action = $params['action'] ?? '';

$uname = $username;
// 打印接收到的所有参数进行调试

switch ($action) {
    case 'getDeviceList':
        getDeviceList($conn, $uname, $params);
        break;
    case 'addDevice':
        addDevice($conn, $uname, $params);
        break;
    case 'deleteDevice':
        deleteDevice($conn, $uname, $params);
        break;
    case 'addGroup':
        addGroup($conn, $uname, $params);
        break;
    case 'deleteGroup':
        deleteGroup($conn, $uname, $params);
        break;
    case 'moveDeviceToGroup':
        moveDeviceToGroup($conn, $uname, $params);
        break;
    case 'batchOperation':
        batchOperation($conn, $uname, $params);
        break;
    default:
        echo json_encode(['Code' => 400, 'Msg' => '无效的操作']);
}



/**
 * 获取设备列表及分组信息（仅当前用户）
 */
function getDeviceList($conn, $uname, $params)
{
    $page = intval($params['currentPage'] ?? 1);
    $pageSize = intval($params['pagesize'] ?? 25);
    $deviceName = $conn->real_escape_string($params['deviceName'] ?? '');
    $pollcode = $conn->real_escape_string($params['pollcode'] ?? '');
    $state = $conn->real_escape_string($params['state'] ?? '全部');
    $scriptState = is_array($params['scriptState'] ?? '') ? $params['scriptState'] : [$params['scriptState'] ?? ''];
    $ids = is_array($params['Id'] ?? '') ? $params['Id'] : [];

    // 查询当前用户的设备
    $sql = "SELECT * FROM devices WHERE uname = '$uname'";

    if (!empty($deviceName)) {
        $sql .= " AND dev_name LIKE '%$deviceName%'";
    }
    if (!empty($pollcode)) {
        $sql .= " AND pollcode LIKE '%$pollcode%'";
    }
    if ($state !== '全部') {
        $sql .= " AND online = " . ($state === '在线' ? 1 : 0);
    }
    if (!in_array('全部状态', $scriptState) && !empty($scriptState[0])) {
        $scriptStateStr = implode("','", array_map([$conn, 'real_escape_string'], $scriptState));
        $sql .= " AND scriptState IN ('$scriptStateStr')";
    }
    if (!empty($ids)) {
        $idsStr = implode(",", array_map('intval', $ids));
        $sql .= " AND id IN ($idsStr)";
    }

    // 获取总数
    $countSql = "SELECT COUNT(*) as total FROM ($sql) as t";
    $countResult = $conn->query($countSql);
    $total = $countResult->fetch_assoc()['total'];

    // 添加排序和分页
    $sql .= " ORDER BY online DESC, time_updata DESC";
    $offset = ($page - 1) * $pageSize;
    $sql .= " LIMIT $offset, $pageSize";

    // 执行查询
    $result = $conn->query($sql);
    $Data = [];
    while ($row = $result->fetch_assoc()) {
        $Data[] = $row;
    }

    // 获取当前用户的分组信息
    $groupSql = "SELECT dg.id, dg.group_name, dg.`order`, dr.device_id, d.dev_name, d.online, d.time_updata 
   FROM device_groups dg 
   LEFT JOIN device_group_relations dr ON dg.id = dr.group_id AND dr.uname = '$uname'
   LEFT JOIN devices d ON dr.device_id = d.id AND d.uname = '$uname'
   WHERE dg.uname = '$uname'
   ORDER BY dg.`order`, dg.id, d.online DESC, d.time_updata DESC";  // 根据 order 字段排序
    $groupResult = $conn->query($groupSql);

    $groups = [];
    while ($row = $groupResult->fetch_assoc()) {
        $groupId = $row['id'];
        if (!isset($groups[$groupId])) {
            $groups[$groupId] = [
                'groupName' => $row['group_name'],
                'Id' => $groupId,
                'order' => $row['order'],  // 添加 order 字段
                'device' => []
            ];
        }
        if ($row['device_id']) {
            $groups[$groupId]['device'][] = [
                'Id' => $row['device_id'],
                'dev_name' => $row['dev_name']
            ];
        }
    }
    // 计算当前用户的在线/离线数量
    $onlineSql = "SELECT COUNT(*) as onlineNum FROM devices WHERE uname = '$uname' AND online = 1";
    $onlineResult = $conn->query($onlineSql);
    $onlineNum = $onlineResult->fetch_assoc()['onlineNum'];

    // 返回结果
    echo json_encode([
        'Code' => 200,
        'Data' => [
            'total' => $total,
            'pagesize' => $pageSize,
            'md5' => md5(json_encode($Data)),
            'Data' => $Data,
            'group' => array_values($groups),
            'onlineNum' => $onlineNum,
            'offlineNum' => $total - $onlineNum,
            'groupMD5' => md5(json_encode($groups)),
            'tokenkey_auto' => 0,
            'exist_pollcode' => !empty($pollcode)
        ]
    ]);
}

/**
 * 添加设备（检查设备名唯一性）
 */
function addDevice($conn, $uname, $params)
{
    $required = ['dev_name'];
    foreach ($required as $field) {
        if (empty($params[$field])) {
            echo json_encode(['Code' => 400, 'Msg' => "缺少必填字段: $field"]);
            return;
        }
    }

    $devName = trim($conn->real_escape_string($params['dev_name']));

    // 检查设备名是否已存在（使用预处理语句）
    $checkSql = "SELECT id FROM devices WHERE uname = ? AND dev_name = ?";
    $stmt = $conn->prepare($checkSql);
    $stmt->bind_param("ss", $uname, $devName);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        echo json_encode(['Code' => 400, 'Msg' => '设备名已存在']);
        $stmt->close();
        return;
    }
    $stmt->close();

    $fields = [
        'uname' => $uname,
        'dev_name' => $devName,
        'pollcode' => $conn->real_escape_string($params['pollcode'] ?? ''),
        'realname' => $conn->real_escape_string($params['realname'] ?? ''),
        'time_add' => time(),
        'time_updata' => time(),
        'state' => intval($params['state'] ?? 1),
        'bindingScriptConfigId' => intval($params['bindingScriptConfigId'] ?? 0),
        'bindingScriptConfigName' => $conn->real_escape_string($params['bindingScriptConfigName'] ?? ''),
        'version' => $conn->real_escape_string($params['version'] ?? '未知'),
        'online' => intval($params['online'] ?? 0),
        'scriptState' => $conn->real_escape_string($params['scriptState'] ?? '离线')
    ];

    $columns = implode(', ', array_keys($fields));
    $placeholders = str_repeat('?,', count($fields) - 1) . '?';
    $sql = "INSERT INTO devices ($columns) VALUES ($placeholders)";

    $types = str_repeat('s', count($fields));
    $values = array_values($fields);

    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$values);

    if ($stmt->execute()) {
        $deviceId = $stmt->insert_id;
        $stmt->close();

        // 默认添加到当前用户的默认分组
        $defaultGroupSql = "SELECT id FROM device_groups WHERE uname = ? AND group_name = '默认分组' LIMIT 1";
        $stmt2 = $conn->prepare($defaultGroupSql);
        $stmt2->bind_param("s", $uname);
        $stmt2->execute();
        $defaultGroupResult = $stmt2->get_result();

        if ($defaultGroupResult->num_rows > 0) {
            $defaultGroup = $defaultGroupResult->fetch_assoc();
            $relationSql = "INSERT INTO device_group_relations (uname, device_id, group_id, create_time) VALUES (?, ?, ?, ?)";
            $stmt3 = $conn->prepare($relationSql);
            $createTime = time();
            $stmt3->bind_param("siii", $uname, $deviceId, $defaultGroup['id'], $createTime);
            $stmt3->execute();
            $stmt3->close();
        }
        $stmt2->close();

        echo json_encode(['Code' => 200, 'Msg' => '设备添加成功', 'Data' => ['id' => $deviceId]]);
    } else {
        $error = $stmt->error;
        $errno = $conn->errno;
        $stmt->close();

        // 检查是否是唯一索引冲突错误
        if ($errno == 1062) { // 1062是MySQL唯一索引冲突错误码
            echo json_encode(['Code' => 400, 'Msg' => '设备名已存在']);
        } else {
            echo json_encode(['Code' => 500, 'Msg' => '设备添加失败: ' . $error]);
        }
    }
}
/**
 * 删除设备（仅能删除当前用户的设备）
 */
function deleteDevice($conn, $uname, $params)
{
    if (empty($params['id']) && empty($params['ids'])) {
        echo json_encode(['Code' => 400, 'Msg' => '缺少设备ID']);
        return;
    }

    $ids = !empty($params['ids']) ? (array)$params['ids'] : [(int)$params['id']];
    $idsStr = implode(',', array_map('intval', $ids));

    // 验证设备是否属于当前用户
    $checkSql = "SELECT COUNT(*) as count FROM devices WHERE uname = '$uname' AND id IN ($idsStr)";
    $checkResult = $conn->query($checkSql);
    $validCount = $checkResult->fetch_assoc()['count'];

    if ($validCount != count($ids)) {
        echo json_encode(['Code' => 403, 'Msg' => '无权操作这些设备']);
        return;
    }

    // 开启事务
    $conn->begin_transaction();

    try {
        // 删除设备分组关系
        $relationSql = "DELETE FROM device_group_relations WHERE uname = '$uname' AND device_id IN ($idsStr)";
        if (!$conn->query($relationSql)) {
            throw new Exception('删除设备分组关系失败: ' . $conn->error);
        }

        // 删除设备
        $deviceSql = "DELETE FROM devices WHERE uname = '$uname' AND id IN ($idsStr)";
        if (!$conn->query($deviceSql)) {
            throw new Exception('删除设备失败: ' . $conn->error);
        }

        $conn->commit();
        echo json_encode(['Code' => 200, 'Msg' => '设备删除成功', 'Data' => ['ids' => $ids]]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['Code' => 500, 'Msg' => $e->getMessage()]);
    }
}

/**
 * 添加分组（检查分组名唯一性）
 */
function addGroup($conn, $uname, $params)
{
    if (empty($params['group_name'])) {
        echo json_encode([
            'Code' => 400,
            'Msg' => '缺少分组名称',
            'Data' => null
        ], JSON_UNESCAPED_UNICODE);
        return;
    }

    $groupName = $conn->real_escape_string($params['group_name']);

    // 检查分组名是否已存在
    $checkSql = "SELECT id FROM device_groups WHERE uname = '$uname' AND group_name = '$groupName'";
    if ($conn->query($checkSql)->num_rows > 0) {
        echo json_encode([
            'Code' => 400,
            'Msg' => '分组名已存在',
            'Data' => null  // 可选：保持结构统一
        ], JSON_UNESCAPED_UNICODE);
        return;
    }

    $time = time();
    $sql = "INSERT INTO device_groups (uname, group_name, create_time, update_time, `order`) 
            VALUES ('$uname', '$groupName', $time, $time, 0)";

    if ($conn->query($sql) === TRUE) {
        echo json_encode([
            'Code' => 200,
            'Msg' => '分组添加成功',
            'Data' => [
                'id' => $conn->insert_id,
                'group_name' => $groupName
            ]
        ]);
        return;
    } else {
        echo json_encode(['Code' => 500, 'Msg' => '分组添加失败: ' . $conn->error]);
        return;
    }
}

/**
 * 删除分组（仅能删除当前用户的分组）
 */
function deleteGroup($conn, $uname, $params)
{
    if (empty($params['id'])) {
        echo json_encode(['Code' => 400, 'Msg' => '缺少分组ID']);
        return;
    }

    $groupId = (int)$params['id'];

    // 验证分组是否属于当前用户
    $checkSql = "SELECT group_name FROM device_groups WHERE uname = '$uname' AND id = $groupId";
    $checkResult = $conn->query($checkSql);
    if ($checkResult->num_rows === 0) {
        echo json_encode(['Code' => 403, 'Msg' => '分组不存在或无权操作']);
        return;
    }

    $group = $checkResult->fetch_assoc();
    if ($group['group_name'] === '默认分组') {
        echo json_encode(['Code' => 400, 'Msg' => '不能删除默认分组']);
        return;
    }

    // 开启事务
    $conn->begin_transaction();

    try {
        // 获取该分组下的设备
        $deviceSql = "SELECT device_id FROM device_group_relations 
                     WHERE uname = '$uname' AND group_id = $groupId";
        $deviceResult = $conn->query($deviceSql);
        $deviceIds = [];
        while ($row = $deviceResult->fetch_assoc()) {
            $deviceIds[] = $row['device_id'];
        }

        // 将这些设备移动到默认分组
        if (!empty($deviceIds)) {
            $defaultGroupSql = "SELECT id FROM device_groups 
                              WHERE uname = '$uname' AND group_name = '默认分组' LIMIT 1";
            $defaultGroupResult = $conn->query($defaultGroupSql);
            if ($defaultGroupResult->num_rows > 0) {
                $defaultGroup = $defaultGroupResult->fetch_assoc();
                $deviceIdsStr = implode(',', $deviceIds);

                // 删除原有关系
                $deleteRelationSql = "DELETE FROM device_group_relations 
                                    WHERE uname = '$uname' AND group_id = $groupId";
                if (!$conn->query($deleteRelationSql)) {
                    throw new Exception('删除分组关系失败: ' . $conn->error);
                }

                // 添加到默认分组
                $values = [];
                $time = time();
                foreach ($deviceIds as $deviceId) {
                    $values[] = "('$uname', $deviceId, {$defaultGroup['id']}, $time)";
                }
                $insertSql = "INSERT INTO device_group_relations (uname, device_id, group_id, create_time) 
                              VALUES " . implode(', ', $values);
                if (!$conn->query($insertSql)) {
                    throw new Exception('移动设备到默认分组失败: ' . $conn->error);
                }
            }
        }

        // 删除分组
        $groupSql = "DELETE FROM device_groups WHERE uname = '$uname' AND id = $groupId";
        if (!$conn->query($groupSql)) {
            throw new Exception('删除分组失败: ' . $conn->error);
        }

        $conn->commit();
        echo json_encode(['Code' => 200, 'Msg' => '分组删除成功']);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['Code' => 500, 'Msg' => $e->getMessage()]);
    }
}

/**
 * 移动设备到分组（权限验证）
 */
function moveDeviceToGroup($conn, $uname, $params)
{
    if (empty($params['device_id']) || empty($params['group_id'])) {
        echo json_encode(['Code' => 400, 'Msg' => '缺少设备ID或分组ID']);
        return;
    }

    $deviceId = (int)$params['device_id'];
    $groupId = (int)$params['group_id'];
    $time = time();

    // 检查设备是否属于当前用户
    $deviceSql = "SELECT id FROM devices WHERE uname = '$uname' AND id = $deviceId";
    if ($conn->query($deviceSql)->num_rows === 0) {
        echo json_encode(['Code' => 403, 'Msg' => '设备不存在或无权操作']);
        return;
    }

    // 检查分组是否属于当前用户
    $groupSql = "SELECT id FROM device_groups WHERE uname = '$uname' AND id = $groupId";
    if ($conn->query($groupSql)->num_rows === 0) {
        echo json_encode(['Code' => 403, 'Msg' => '分组不存在或无权操作']);
        return;
    }

    // 删除原有关系
    $deleteSql = "DELETE FROM device_group_relations 
                 WHERE uname = '$uname' AND device_id = $deviceId";
    if (!$conn->query($deleteSql)) {
        echo json_encode(['Code' => 500, 'Msg' => '清除原有分组关系失败: ' . $conn->error]);
        return;
    }

    // 添加新关系
    $insertSql = "INSERT INTO device_group_relations (uname, device_id, group_id, create_time) 
                  VALUES ('$uname', $deviceId, $groupId, $time)";
    if ($conn->query($insertSql)) {
        echo json_encode(['Code' => 200, 'Msg' => '移动分组成功']);
    } else {
        echo json_encode(['Code' => 500, 'Msg' => '移动分组失败: ' . $conn->error]);
    }
}

/**
 * 更新分组名称或排序
 */
function updateGroup($conn, $uname, $params) {
    $groupId = intval($params['id'] ?? 0);
    $field = $params['field'] ?? '';
    $value = $params[$field] ?? '';

    if ($groupId <= 0 || empty($field) || empty($value)) {
        echo json_encode(['Code' => 400, 'Msg' => '参数错误']);
        return;
    }

    // 验证分组是否属于当前用户
    $checkSql = "SELECT id FROM device_groups WHERE uname = '$uname' AND id = $groupId";
    if ($conn->query($checkSql)->num_rows === 0) {
        echo json_encode(['Code' => 403, 'Msg' => '分组不存在或无权操作']);
        return;
    }

    // 更新分组信息
    $updateSql = "UPDATE device_groups SET $field = '$value', update_time = UNIX_TIMESTAMP() 
                 WHERE id = $groupId AND uname = '$uname'";
    
    if ($conn->query($updateSql)) {
        echo json_encode(['Code' => 200, 'Msg' => '更新成功']);
    } else {
        echo json_encode(['Code' => 500, 'Msg' => '更新失败: ' . $conn->error]);
    }
}
/**
 * 批量操作（权限验证）
 */
function batchOperation($conn, $uname, $params)
{
    if (empty($params['command']) || empty($params['device_ids'])) {
        echo json_encode(['Code' => 400, 'Msg' => '缺少操作命令或设备ID']);
        return;
    }

    $command = $conn->real_escape_string($params['command']);
    $deviceIds = is_array($params['device_ids']) ? $params['device_ids'] : [$params['device_ids']];
    $deviceIdsStr = implode(',', array_map('intval', $deviceIds));
    $time = time();

    // 验证设备是否属于当前用户
    $checkSql = "SELECT COUNT(*) as count FROM devices WHERE uname = '$uname' AND id IN ($deviceIdsStr)";
    $checkResult = $conn->query($checkSql);
    $validCount = $checkResult->fetch_assoc()['count'];

    if ($validCount != count($deviceIds)) {
        echo json_encode(['Code' => 403, 'Msg' => '无权操作这些设备']);
        return;
    }

    // 根据不同的命令执行不同的操作
    switch ($command) {
        case 'runScript':
        case 'reRun':
            $sql = "UPDATE devices SET scriptState = '运行中', online = 1, time_updata = $time 
                    WHERE uname = '$uname' AND id IN ($deviceIdsStr)";
            break;
        case 'pauseScript':
            $sql = "UPDATE devices SET scriptState = '暂停中', time_updata = $time 
                    WHERE uname = '$uname' AND id IN ($deviceIdsStr)";
            break;
        case 'resumeScript':
            $sql = "UPDATE devices SET scriptState = '运行中', time_updata = $time 
                    WHERE uname = '$uname' AND id IN ($deviceIdsStr)";
            break;
        case 'stopScript':
            $sql = "UPDATE devices SET scriptState = '已停止', online = 0, time_updata = $time 
                    WHERE uname = '$uname' AND id IN ($deviceIdsStr)";
            break;
        case 'bindScriptConfig':
            if (empty($params['script_config_id']) || empty($params['script_config_name'])) {
                echo json_encode(['Code' => 400, 'Msg' => '缺少脚本配置ID或名称']);
                return;
            }
            $configId = (int)$params['script_config_id'];
            $configName = $conn->real_escape_string($params['script_config_name']);
            $sql = "UPDATE devices SET bindingScriptConfigId = $configId, 
                    bindingScriptConfigName = '$configName', time_updata = $time 
                    WHERE uname = '$uname' AND id IN ($deviceIdsStr)";
            break;
        case 'unbindScriptConfig':
            $sql = "UPDATE devices SET bindingScriptConfigId = 0, 
                    bindingScriptConfigName = '', time_updata = $time 
                    WHERE uname = '$uname' AND id IN ($deviceIdsStr)";
            break;
        case 'updateGroup':
            updateGroup($conn, $uname, $params);
            break;
        default:
            echo json_encode(['Code' => 400, 'Msg' => '不支持的操作命令']);
            return;
    }

    if ($conn->query($sql)) {
        echo json_encode(['Code' => 200, 'Msg' => '批量操作成功', 'Data' => ['command' => $command]]);
    } else {
        echo json_encode(['Code' => 500, 'Msg' => '批量操作失败: ' . $conn->error]);
    }
}
